<!--
  采购订单管理
 -->

<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="53"
        :add-active="true"
        :del-active="delActive"
        :edit-active="editActive"
        :has-cancel="false"
        :has-save="false"
        :has-edit="false"
        :has-del="false"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div v-if="curTabIndex == 0" class="common-search-item">
          <div class="label">关联采购订单编号:</div>
          <div class="input">
            <el-select
              v-model="searchInfo.orderNo"
              placeholder="请选择"
              filterable
              clearable
            />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">入库单:</span>
          <div class="input">
            <el-input v-model="searchInfo.purchaserName" />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">接收人:</span>
          <div class="input">
            <el-input v-model="searchInfo.personNo" />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">入库仓库:</span>
          <div class="input">
            <el-input v-model="searchInfo.warehouseNo" />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">入库日期:</span>
          <div class="input">
            <StartTimeEndTimeSelectionBox @startVal="startVal" @endVal="endVal" />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="returnOrderNo" label="退货单号" min-width="100" />
        <el-table-column prop="targetOrderNo" label="对应单号" min-width="100" />
        <el-table-column prop="warehouseName" label="仓库" />
        <el-table-column prop="returnDate" :formatter="dateFormat" label="退货日期" min-width="100" />
        <el-table-column prop="supplyProducts" label="入库图片">
          <template v-if="scope.row.returnOrderNo" slot-scope="scope">
            <el-button v-if="scope.row.pictureNoList.length" class="text-btn-cursor" type="text" size="small" @click="showimgmet(scope.row)">查看</el-button>
            <span v-else>暂无</span>
          </template>
        </el-table-column>
        <el-table-column width="200" label="退货产品">
          <template v-if="scope.row.returnOrderNo" slot-scope="scope">
            <el-button type="text" class="text-btn-cursor" @click="handledbCheck(scope.row)"><i class="el-icon-view"></i> 查看</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column width="100" label="操作">
          <template v-if="scope.row.returnOrderNo" slot-scope="scope">
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <!-- 展示图片 -->
      <el-dialog
        title="执照图片"
        :visible.sync="isshowimg"
        width="30%"
      >
        <img :src="nowimgurl" width="100%" height="auto" />
      </el-dialog>
      <!-- 订单退货 -->
      <el-dialog
        :title="titleText + '订单退货'"
        :visible.sync="dialogFormVisible"
        :before-close="handleClose"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="退货日期:" class="w50p" prop="returnDate">
            <el-date-picker
              v-model="formData.returnDate"
              type="date"
              placeholder="选择时间"
              :disabled="!canInput"
              value-format="timestamp"
            />
          </el-form-item>
          <el-form-item label="退货类型:" class="w50p" prop="returnType">
            <el-select
              v-model="formData.returnType"
              :disabled="!canInput"
              clearable
              filterable
              @change="getOrderList"
            >
              <el-option
                v-for="(item, index) in returnTypeList"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="对应单号:" class="w50p" prop="targetOrderNo">
            <el-select
              v-model="formData.targetOrderNo"
              :disabled="!canInput"
              clearable
              filterable
              @change="getGoodsList"
            >
              <el-option
                v-for="(item, index) in orderList"
                :key="index"
                :label="item.no"
                :value="item.no"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="退货图片:" prop="pictureNo" class="w50p">
            <ele-upload-image
              v-model="image"
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :headers="headers"
              :action="ImageUrl()"
            />
          </el-form-item>
          <el-row>
            <h4 class="total-price">
              <span>退货产品明细:</span>
              <span>总金额:{{ totalPrice }}元</span>
            </h4>
            <el-table
              ref="rightTableData"
              :data="rightTableData"
              tooltip-effect="dark"
              highlight-current-row
              border
              stripe
              class="rightTableData"
              @selection-change="selectRow"
            >
              <el-table-column type="index" label="序号" width="50" />
              <el-table-column label="物品名称" prop="goodsName" align="center" min-width="120" />
              <el-table-column label="规格" prop="specification" />
              <el-table-column label="型号" prop="model" />
              <el-table-column label="单价" prop="price">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.price" />
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="quantity" min-width="95">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.quantity" />
                </template>
              </el-table-column>
              <el-table-column label="单位" min-width="75" prop="unitName" />
              <el-table-column label="优惠金额" prop="favorablePrice" min-width="95">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.favorablePrice" />
                </template>
              </el-table-column>
              <el-table-column
                label="物品总价"
                prop="totalAmount"
                min-width="95"
              />
              <template slot="empty">
                <div>请添加数据</div>
              </template>
            </el-table>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <!-- 入库产品 -->
      <el-dialog
        title="详细信息"
        :visible.sync="purchaseVisible"
        width="60%"
        class="purchase"
      >
        <el-row>
          <h4 class="total-price">
            <span>采购物品明细:</span>
            <span>采购总金额:{{ totalPrice }}元</span>
          </h4>
          <el-table
            ref="rightTableData"
            :data="rightTableData"
            tooltip-effect="dark"
            highlight-current-row
            border
            stripe
            class="rightTableData"
            @selection-change="selectRow"
          >
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column label="物品名称" prop="goodsName" align="center" min-width="120" />
            <el-table-column label="规格" prop="specification" />
            <el-table-column label="型号" prop="model" />
            <el-table-column label="单价" prop="price" />
            <el-table-column label="入库数量" prop="quantity" min-width="95" />
            <el-table-column label="单位" min-width="75" prop="unitName" />
            <el-table-column label="优惠金额" prop="favorablePrice" min-width="95" />
            <el-table-column
              label="物品总价"
              prop="totalPriceItem"
              min-width="95"
            />
            <el-table-column label="操作" min-width="80">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="color:red;text-decoration: underline;"
                  :disabled="!canInput"
                  size="small"
                  @click.native.prevent="
                    deleteRow(scope.$index, rightTableData)
                  "
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
            <template slot="empty">
              <div>请添加数据</div>
            </template>
          </el-table>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-two" type="primary" @click="purchaseVisible = false">
            确 定
          </el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SearchBox from "@/components/SearchBox";
import { mymixin } from "@/utils/mixin";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
// import SelectButton from "@/components/selectbutton/index.vue"
import warehouseInventory from "@/api/digital-operation/warehouse-inventory";
// import purchaseOrderManage from "@/api/digital-operation/purchase-manage/purchase-order-manage";
import warehouseManage from "@/api/basic-info-manage/warehouse-manage";
// import productManage from "@/api/basic-info-manage/product-manage"
// import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import baseURL from "@/api/baseURL";
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "return-goods-manage",
  components: {
    BaseMainSlot,
    ActionBar,
    Pagination,
    StartTimeEndTimeSelectionBox,
    SearchBox
    // SelectButton
  },
  mixins: [mymixin],
  data() {
    return {
      nowimgurl: null,
      isshowimg: false,
      image: null,
      searchInfo: {},
      // 名称
      name: "",
      nameList: [],
      price: "",
      number: "",
      // 采购物品
      goodsId: "",
      goodsList: [],
      unitName: "",
      rulesTime: "",
      // 人員名稱
      purchaser: "",
      // 供應商名稱
      supplierId: "",
      totalPrice: 0,
      // 采购订单名称
      orderNumber: "",
      agriculturalMaterialName: "",
      StaffData: [],
      // 采购部门列表
      supplierList: [],
      paramNamelist: [],
      selectlistRow: [],
      salseProductsName: [],
      // 农资类型
      agriMateArr: [],
      returnTypeList: [{ name: '出库退货', value: 0 }, { name: "入库退货", value: 1 }],
      rightTableData: [],
      // addformData 添加的表单
      addformData: {},
      // 控制表格 添加行 input 显示隐藏
      addHide: true,
      purchaseVisible: false,
      dialogFormVisible: false,
      endTime: "",
      startTime: "",
      titleText: "",
      startDatePickers: this.beginDates(),
      endDatePickers: this.processDates(),
      rules: {
        purchaseOrderNo: [
          { required: true, message: "请选择采购订单", trigger: "change" }
        ]
      },
      rulesTwo: {

      },
      curTabIndex: 0,
      warehouseList: [],
      warehousingProductTypeList: ["成品", "半成品", "物料"],
      warehousingSourceList: ["生产", "加工"],
      orderList: []
    };
  },
  computed: {
    headers() {
      return {
        loginToken: sessionStorage.getItem("token"),
        organizationNo: sessionStorage.organizationNo,
        sysDataBaseName: sessionStorage.databaseName
      };
    }
  },
  watch: {
    rightTableData: {
      deep: true,
      handler(val) {
        let arr = [];
        val.forEach(item => {
          if (item.quantity && item.price) {
            arr.push(parseFloat(item.quantity) * parseFloat(item.price) - parseFloat(item.favorablePrice || '0'));
            item.totalAmount = (
              parseFloat(item.quantity) * parseFloat(item.price) - parseFloat(item.favorablePrice || '0')
            ).toFixed(2);
          } else {
            item.totalAmount
          }
        });
        sum(arr);
        function sum(arr) {
          var s = 0;
          for (var i = arr.length - 1; i >= 0; i--) {
            s += arr[i];
          }
          return s;
        }
        this.totalPrice = sum(arr).toFixed(2) || 0;
        // console.log(sum(arr))
      }
    },
    addformData: {
      deep: true,
      handler(val) {
        // console.log(val)
        if (val.number && val.price) {
          // 当input值改变时计算
          this.$set(
            val,
            "totalPriceItem",
            (parseFloat(val.number) * parseFloat(val.price)).toFixed(2)
          );
        }
      }
    }
  },
  created() {
    this.queryDatalist()
  },
  mounted() {
    // 表格分页数据
    this.getTableDataList();
  },
  methods: {
    // 展示图片
    showimgmet(e) {
      if (e.pictureNoList && e.pictureNoList.length) {
        warehouseInventory.getReturnOrderPicture(e.pictureNoList[0]).then(res => {
          this.nowimgurl = 'data:image/png;base64,' + res.data.pictureData
          this.isshowimg = true
        })
      } else {
        this.$message.warning('暂无图片')
      }
    },
    // 图片地址
    ImageUrl() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let URL = `${baseURL.webServiceUrl}v3/warehouse/returnOrderPicture/add`;
        return URL;
      } else {
        let URL = "#";
        // console.log(URL)
        return URL;
      }
    },
    handleResponse(response, file, fileList) {
      // return this.basicUrl + query/ + this.pictureNo
      this.pictureNo = response.data;
      warehouseInventory.getReturnOrderPicture(this.pictureNo).then(res => {
        this.image = "data:image/png;base64," + res.data.pictureData;
      })
      return this.image;
    },
    handleRemove() {
      if (this.nowChanceStau === "edit") {
        // console.log(response);
        warehouseInventory.delReturnOrderPicture(this.pictureNo).then(res => {
          if (res.code === 1) {
            delete this.pictureNo;
            delete this.formData.pictureNo;
            this.$message.success(res.msg);
          }
        });
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    batchstaumet(index) {
      this.curTabIndex = index;
      this.getTableDataList();
    },
    // 获取 表格数据
    getTableDataList() {
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        sort: "timestamp",
        entity: {
          ...this.searchInfo
        }
      };
      warehouseInventory.queryPageByConditionReturnOrder(param).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          // console.log(data);
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    async queryDatalist() {
      // 查询采购订单
      // const { data: SellOrder } = await purchaseOrderManage.queryByCondition()
      // this.returnTypeList = SellOrder;

      // // 查询客户名称
      // const { data: supplie } = await supplierManage.supplierName()
      // this.paramNamelist = supplie;
      // // 查询员工
      // const { data: Staff } = await StaffManage.getStaffListByCondition()
      // this.StaffData = Staff;
      // const { data: topitem } = await baseQuery.baseQueryByCondition()
      // // 查询农资名称
      // let topitemidList = topitem.map(item => item.farmingTypeNo)
      // const { data: agriMate } = await agriMateManage.queryAgriculturalList(topitemidList)
      // this.agriMateArr = agriMate;
    },
    async getWarehouseList() {
      // 查询仓库列表
      let params = { warehouseSystem: '生产', warehouseTypeName: this.formData.warehousingProductType };
      const { data: warehouseList } = await warehouseManage.getWareHouseListByCondition(params);
      this.warehouseList = warehouseList;
    },
    async getOrderList(type) {
      this.orderList = [];
      if (type === 0) {
        // 出库单查询
        let res = await warehouseInventory.queryByConditionOutboundOrder({});
        let list = res.data;
        list.forEach(item => {
          this.orderList.push({
            no: item.outboundOrderNo,
            warehouseNo: item.warehouseNo
          })
        })
      } else {
        // 入库单查询
        let res = await warehouseInventory.queryByConditionWarehouseOrder({});
        let list = res.data;
        list.forEach(item => {
          this.orderList.push({
            no: item.warehousingOrderNo,
            warehouseNo: item.warehouseNo
          })
        })
      }
    },
    async getGoodsList(no) {
      let obj = this.orderList.find(el => el.no === no);
      this.formData.warehouseNo = obj.warehouseNo;
      if (this.formData.returnType === 0) {
        // 出库货物
        const { data: dataList } = await warehouseInventory.getOutboundGoodsByNo(no);
        dataList.forEach(item => {
          item.price = item.unitPrice;
        })
        this.rightTableData = dataList;
      } else {
        // 入库货物
        const { data: dataList } = await warehouseInventory.getWarehousingGoodsByNo(no);
        this.rightTableData = dataList;
      }
      // 查询入库产品列表
    },
    // 搜索框时间
    startVal(e) {
      this.searchInfo.returnStartDate = e
    },
    endVal(e) {
      this.searchInfo.returnEndDate = e
    },
    beginDates() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.deliveryTime) {
            //  如果结束时间不为空，则小于结束时间
            return (
              new Date(self.formData.deliveryTime).getTime() < time.getTime()
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDates() {
      const self = this;
      // if (self.endTime) {
      return {
        disabledDate(time) {
          if (self.formData.procurementTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return (
              new Date(self.formData.procurementTime).getTime() > time.getTime()
            );
          } else {
            return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },

    selectRow(val) {
      this.selectlistRow = val;
    },
    // 点击添加按按钮
    addButInfo() {
      let list = {
        name: '',
        number: '',
        unitName: '',
        price: '',
        totalPriceItem: '',
        agriculturalMaterialId: ''
      }
      this.rightTableData.unshift(list);
      this.addformData = {};
    },
    // 删除改行
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    selectable(row, index) {
      return row.status === true // 通过某个值来进行判断，规定那一行的选择框被禁用
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 时间
    dateFormat(row, colnum) {
      if (row.returnOrderNo) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD");
      }
    },
    // add(){
    //   this.rightTableData = [];
    //   this.canInput = true;
    //   this.nowChanceStau = 'add';
    //   this.dialogFormVisible = true;
    //   this.formData = {};
    // },
    async handledbCheck(row) {
      if (row.returnOrderNo) {
        this.formData = JSON.parse(JSON.stringify(row));
        let { data: goodList } = await warehouseInventory.getReturnGoodsByNo(row.returnOrderNo);
        this.rightTableData = goodList;
        this.purchaseVisible = true;
      }
    },
    handleSelectionChange(list) {
      this.purchaseOrderIdList = [];
      this.purchaseOrderIdList = list.map(item => item.purchaseOrderId);
      if (this.purchaseOrderIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          // 来料入库
          this.formData.totalAmount = this.totalPrice;
          this.formData.goodList = this.rightTableData;
          this.formData.organizationNo = sessionStorage.organizationNo;
          this.formData.pictureNoList = [this.pictureNo];
          warehouseInventory.addReturnOrder(this.formData).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg || "新增成功！");
              this.dialogFormVisible = false;
              this.getTableDataList();
              this.$refs[formData].resetFields()
            } else {
              this.$message.error(res.msg || "新增失败！");
            }
          });
        }
      });
    },
    handleClose(done) {
      this.resetActionBar();
      done();
    },
    tableAgriMate(scope) {
      let obj = {};
      if (this.formDataTwo.warehousingProductType === '物料') {
        obj = this.goodsList.find(item => item.materialNo === scope.row.goodsNo);
        obj.goodsName = obj.materialName;
      } else {
        obj = this.goodsList.find(item => item.productNo === scope.row.goodsNo);
        obj.goodsName = obj.productName;
      }
      this.$set(this.rightTableData, scope.$index, obj)
    },
    handleDelete(row) {
      warehouseInventory.delReturnOrder(row.returnOrderNo).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getTableDataList();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      });
    }

  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.search-item {
  display: flex;
  height: 36px;
  margin-left: 20px;
  white-space: nowrap;
  &:first-child {
    margin: 0;
  }
  span {
    display: inline-block;
  }
  &.rules-wrap span {
    padding: 0 15px;
    border: 1px solid $borderColor;
    cursor: pointer;
    line-height: 35px;
    transition: border-color 0.2s;
    box-sizing: border-box;
    &:hover {
      border-color: #6ecae3;
    }
  }
}
.purchase {
  ::v-deep .el-dialog {
    border: 1px solid #000;
    border-radius: 10px;
    .el-dialog__header {
      border-radius: 9px 9px 0 0;
      .el-dialog__title {
        color: #fff;
      }
    }
    .el-dialog__body {
      padding: 5px 20px;
      font-size: 12px !important;
      .el-input {
        input {
          font-size: 12px;
        }
      }
    }
    .el-table {
      max-height: 200px;
      overflow-y: auto;
      background-color: rgba(255, 255, 255, 1);
      .cell {
        color: #000;
      }
      th {
        background-color: rgba(230, 230, 230, 1);
      }
      th.is-leaf {
        border-color: rgba(77, 77, 77, 1);
      }
      td {
        border-color: rgba(77, 77, 77, 1);
      }
      tr:hover {
        background-color: rgba(77, 77, 77, 1);
      }
      .el-table__empty-text {
        color: #000;
      }
      .current-row {
        // background-color: rgb(177, 177, 177);
        background-color: #dbdbdb !important;
      }
      .el-table__row--striped {
        background-color: rgba(255, 255, 255, 1);
      }
      // color: #000;
    }
    .el-table--border {
      border-color: rgba(77, 77, 77, 1);
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .el-table--enable-row-hover .el-table__body tr:hover > td {
      background-color: rgb(177, 177, 177);
    }
    .el-table__body tr.current-row > td {
      background-color: #dbdbdb !important;
    }
    .el-form-item {
      margin-bottom: 10px;
    }
    .total-price {
      color: #000;
    }
    .el-table__body {
      // height: ;
      height: 0;
      // background-color: #003947;
    }
  }
}
.el-date-editor,
.el-select {
  width: 100%;
}

h4.total-price {
  display: flex;
  justify-content: space-between;
  margin: 0;
  color: #fff;
  margin-bottom: 5px;
}

.right-table {
  line-height: 0px;
}
.addInfo {
  width: 100%;
}
.rightTableData {
  // .
  ::v-deep .el-table--border {
    border: #5fb6cd;
  }
  ::v-deep .cell {
    margin: 0 !important;
    // padding: 0 !important;
    font-size: 10px;
  }
  ::v-deep .el-table th {
    margin: 0 !important;
    padding: 0 !important;
    font-size: 10px;
  }
  ::v-deep .el-table--medium th {
    margin: 0 !important;
    padding: 0 !important;
    font-size: 10px;
  }
}
.total {
  ::v-deep .el-input__inner {
    border-right: 1px solid #6ecae3 !important;
  }
}
::v-deep .el-dialog__wrapper{
  .el-dialog {
  // width: 70% !important;
  .el-select {
    width: 100% !important;
  }
  .el-dialog__body {
    .el-form {
      .el-row {
        .el-table {
          max-height: 267px !important;
          .el-table__header-wrapper {
            position: fixed;
            z-index: 99;
          }
          .el-table__body-wrapper {
            margin-top: 38px;
          }
        }
      }
      }
  }}
}
</style>
